import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/common/theme/app_colors.dart';
import 'package:flutter_taotaoshipin/http/dao/drama_dao.dart';
import 'package:flutter_taotaoshipin/model/drama_main_search_entity.dart';
import 'package:flutter_taotaoshipin/model/drama_ranking_entity.dart';
import 'package:flutter_taotaoshipin/pages/drama/view/drama_rank_item.dart';
import 'package:flutter_taotaoshipin/value/sp_key.dart';
import 'package:flutter_taotaoshipin/widget/gaps.dart';
import 'package:flutter_taotaoshipin/widget/my_scroll_view.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hi_net/core/hi_error.dart';

/// 搜索页
class DramaSearchPage extends StatefulWidget {
  const DramaSearchPage({super.key});

  @override
  State<DramaSearchPage> createState() => _DramaSearchPageState();
}

class _DramaSearchPageState extends State<DramaSearchPage> {
  List<DramaRankingEntity> _dramaRankingList = [];
  List<DramaMainSearchEntity> _dramaMainSearchList = [];
  List<String> _searchHisList = [];
  // 已经搜索过了
  bool _hasSearch = false;
  TextEditingController _editingController = TextEditingController();

  @override
  void initState() {
    // 初始化数据
    _initData();
    super.initState();
    _loadRankingData();
  }

  @override
  void dispose() {
    SpUtil.putStringList(SpKey.searchHistory, _searchHisList);
    _editingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          padding: const EdgeInsets.all(12.0),
          tooltip: 'Back',
          onPressed: () {
            // 失去焦点
            FocusManager.instance.primaryFocus?.unfocus();
            Get.back();
          },
          icon: Icon(Icons.arrow_back_ios_new),
        ),
        titleSpacing: 0,
        title: Container(
          height: 35,
          child: TextField(
            autofocus: true,
            textInputAction: TextInputAction.search,
            controller: _editingController,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.zero,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(30.0),
                borderSide: BorderSide.none,
              ),
              filled: true,
              fillColor: Colors.white,
              prefixIcon: Icon(Icons.search),
              hintText: '请输入剧名搜索',
            ),
            onSubmitted: (value) {
              var result = value.trim();
              if (result.isEmpty) return;
              _hasSearch = true;
              _searchHisList.addIf(
                  !_searchHisList.contains(result), result);
              setState(() {});
              _loadSearchData(result);
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              var result = _editingController.text.trim();
              if (result.isEmpty) return;
              _hasSearch = true;
              _searchHisList.addIf(
                  !_searchHisList.contains(result), result);
              setState(() {});
              _loadSearchData(result);
            },
            child: Text('搜索'),
          ),
        ],
      ),
      body: MyScrollView(
        padding:
            EdgeInsets.only(bottom: MediaQuery.of(context).viewPadding.bottom),
        children: [
          if (_searchHisList.isNotEmpty) _searchHistory(),
          if (_dramaRankingList.isNotEmpty && !_hasSearch)
            _hotRecommend(),
          if (_hasSearch) _searchResult(),
        ],
      ),
    );
  }

  _searchHistory() {
    return Container(
      padding: const EdgeInsets.all(15),
      child: Column(
        children: [
          Row(
            children: [
              const Expanded(
                child: Text(
                  '历史搜索',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
              ),
              InkWell(
                onTap: () {
                  setState(() {
                    _searchHisList.clear();
                  });
                },
                child: Row(
                  children: const [
                    Icon(
                      Icons.delete,
                      color: Colors.grey,
                      size: 14,
                    ),
                    Text(
                      '清空',
                      style: TextStyle(fontSize: 14, color: Colors.grey),
                    ),
                  ],
                ),
              ),
            ],
          ),
          Gaps.vGap15,
          SizedBox(
            width: double.infinity,
            child: Wrap(
              spacing: 12,
              runSpacing: 12,
              children: List.generate(
                _searchHisList.length,
                (index) => GestureDetector(
                  onTap: () {
                    _hasSearch = true;
                    _editingController.text = _searchHisList[index];
                    setState(() {});
                    _loadSearchData(_searchHisList[index]);
                  },
                  child: Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 15, vertical: 5),
                    decoration: BoxDecoration(
                      border: Border.all(color: AppColors.app_main),
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: Text(
                      _searchHisList[index],
                      style: TextStyle(color: AppColors.app_main),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _hotRecommend() {
    return Container(
      padding: const EdgeInsets.all(15),
      width: double.infinity,
      child: Column(
        children: [
          Row(
            children: const [
              Expanded(
                child: Text(
                  '热播推荐',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
              ),
            ],
          ),
          Gaps.vGap15,
          ...List.generate(
            _dramaRankingList.length,
            (index) => DramaRankItem(
              model: _dramaRankingList[index],
              rank: index + 1,
            ),
          ),
        ],
      ),
    );
  }

  _searchResult() {
    return Container(
      padding: const EdgeInsets.all(15),
      width: double.infinity,
      child: Column(
        children: [
          Row(
            children: const [
              Expanded(
                child: Text(
                  '搜索列表',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
          Gaps.vGap15,
          ...List.generate(
            _dramaMainSearchList.length,
            (index) {
              var search = _dramaMainSearchList[index];
              var model = DramaRankingEntity().copyWith(
                dramaId: search.id,
                dramaName: search.title,
                img: search.cover,
                desc: search.desc,
                allEp: search.allEp,
              );
              return DramaRankItem(
                model: model,
                rank: index + 1,
              );
            },
          ),
        ],
      ),
    );
  }

  Future<void> _loadRankingData() async {
    try {
      var result = await DramaDao.getDramaRanking();
      if (result.code == 0) {
        // 成功
        if (result.data != null) {
          _dramaRankingList = result.data!;
          setState(() {});
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } on HiNetError catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }
  }

  Future<void> _loadSearchData(String name) async {
    try {
      var result = await DramaDao.getDramaMainSearch(name);
      if (result.code == 0) {
        // 成功
        if (result.data != null) {
          _dramaMainSearchList = result.data!;
          setState(() {});
        } else {
          _dramaMainSearchList.clear();
          setState(() {});
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } on HiNetError catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }
  }

  void _initData() {
    _searchHisList =
        SpUtil.getStringList(SpKey.searchHistory, defValue: [])!;
  }
}
